<template>
    <div>
        <el-dialog v-model="props.isShow" :title="props.isAdd ? '添加商品分类' : '编辑商品分类'" center :before-close="beforeClose">
            <el-form :model="cateForm" :rules="rules" ref="cateRef">
                <el-form-item label="上级分类" :label-width="formLabelWidth" prop="pid">
                    <el-select v-model="cateForm.pid" placeholder="请选择上级分类">
                        <el-option label="顶级菜单" :value="0" />
                        <el-option v-for="item in store.getters['cate/getCateList']" :label="item.catename" :key="item.id"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="分类名称" :label-width="formLabelWidth" prop="catename">
                    <el-input v-model="cateForm.catename" autocomplete="off" />
                </el-form-item>
                <!-- 图片上传 -->
                <el-form-item label="图片" :label-width="formLabelWidth">
                    <el-upload v-model:file-list="fileList" action="#" list-type="picture-card" :auto-upload='false'
                        :limit="1" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-change="changeImg">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>

                    <!-- 预览图片 -->
                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>

                </el-form-item>

                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="cateForm.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="1"
                        :inactive-value="2" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel(cateRef)">取消</el-button>
                    <el-button type="primary" @click="confirm(cateRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang='ts' setup>
import { defineProps, ref, reactive, defineEmits, defineExpose } from 'vue';
import type { FormInstance, FormRules, UploadProps, UploadUserFile, UploadFile, UploadFiles } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { cateadd, cateedit, cateinfo } from '@/request/api';
import store from '@/store';

let cateRef = ref();

// 图片临时路径
const imageUrl = ref('');

// 接收父组件传递过来的值
let props = defineProps({
    isAdd: Boolean,
    isShow: Boolean
})

// 表单
let cateForm = ref({
    pid: 0,//上级分类编号
    catename: '',//商品分类名称
    img: [],//图片(文件，一般用于二级分类)
    status: 1,//状态     1正常2禁用
})

// 规则
const rules = reactive<FormRules>({
    catename: [
        { required: true, message: '请输入分类名称', trigger: 'blur' },
        { min: 2, max: 6, message: '长度在2-6位字符', trigger: 'blur' },
    ],
    pid: [
        {
            required: true,
            message: '请选择上级分类',
            trigger: 'change',
        },
    ],

})

const formLabelWidth = '120px';


const fileList = ref<any[]>([])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)


// 删除图片
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}
// 预览图片
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

// 改变图片
const changeImg = (uploadFile: any, uploadFiles: any) => {
    // console.log(uploadFile,uploadFiles);
    // 处理表单数据   赋值图片
    cateForm.value.img = uploadFile.raw;

}
// 点击x关闭弹窗 清空表单
const beforeClose = (done: any) => {
    done();
    cancel(cateRef.value)
}


// 调用子传父方法
let emit = defineEmits(['cancel']);

// 取消
const cancel = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    emit('cancel')
    // 重置表单
    cateForm.value = {
        pid: 0,//上级分类编号
        catename: '',//商品分类名称
        img: [],//图片(文件，一般用于二级分类)
        status: 1,//状态     1正常2禁用
    }

    // 置空图片
    fileList.value = [];

    // 清空验证
    formEl.resetFields();
}

let newId = 0;

// 数据回显
const lookup = (id: number) => {
    // console.log(id,'回显');
    cateinfo({ id }).then((res: any) => {
        if (res.code == 200) {
            cateForm.value = res.list;
            newId = id;
            // 处理图片
            fileList.value = cateForm.value.img ? [{ url: cateForm.value.img }] : []

        }
    })

}

// 确定
const confirm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate(val => {
        if (val) {
            if (props.isAdd) {
                // 添加
                cateadd(cateForm.value).then(res => {
                    if (res.code == 200) {
                        // 添加成功
                        ElMessage.success(res.msg);
                        // 关闭弹窗
                        cancel(cateRef.value);
                        // 重新渲染列表
                        store.dispatch('cate/getCatelistActions')
                    } else {
                        // 添加失败
                        ElMessage.error(res.msg);
                    }
                })

            } else {
                console.log(cateForm,'编辑');
// return
                // 编辑
                cateedit({...cateForm.value,id:newId}).then(res => {
                    if (res.code == 200) {
                        // 编辑成功
                        ElMessage.success(res.msg);
                        // 关闭弹窗
                        cancel(cateRef.value);
                        // 重新渲染列表
                        store.dispatch('cate/getCatelistActions')
                    } else {
                        // 编辑失败
                        ElMessage.error(res.msg);
                    }
                })
            }
        }
    })
}

defineExpose({
    lookup
})
</script>
<style scoped lang='less'>
// .avatar {
//   width: 178px;
//   height: 178px;
//   display: block;
// }
// .el-upload {
//     border: 1px dashed  #ccc;
//     border-radius: 6px;
//     cursor: pointer;
//     position: relative;
//     overflow: hidden;
//     transition: var(--el-transition-duration-fast);
// }

//  .el-upload:hover {
//     border-color: #ccc;
// }

// .el-icon.avatar-uploader-icon {
//     font-size: 28px;
//     color: #8c939d;
//     width: 178px;
//     height: 178px;
//     text-align: center;
// }


.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>